package com.lsp.helper;

import javax.servlet.http.HttpServletRequest;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * 前端控制器接收到HTTP请求后，从HTTP中获取参数，然后封装到Param对象中
 */
public final class RequestHelper {

    public static Object creteParam(HttpServletRequest request, Method controllerMethod) {
        Map<String, Object>  paramMap = new HashMap<>();
        Enumeration<String> parameterNames = request.getParameterNames();
        if(!parameterNames.hasMoreElements()){return null;}

        Object newInstance = null;
        try {
            //获取参数类型
            Class<?>[] parameterTypes = controllerMethod.getParameterTypes();
            for(Class<?> parameterType : parameterTypes){
                newInstance = parameterType.newInstance();
                //get和post参数都能获取到
                while (parameterNames.hasMoreElements()){
                    String fileName = parameterNames.nextElement();
                    String fileValue = request.getParameter(fileName);

                    PropertyDescriptor pd =  new PropertyDescriptor(fileName,  parameterType);
                    Method writeMethod = pd.getWriteMethod();
                    writeMethod.invoke(newInstance,fileValue);
                }
             }
            }catch (Exception e){
                e.printStackTrace();
            }
        return newInstance;
    }
}
